/**
 * @ClassName KP35_hasPathSum
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/11/1 11:51
 */
public class KP35_HasPathSum {
    // 测试链接：https://leetcode.com/problems/path-sum

    public static class TreeNode {
        public int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public static boolean isSum = false;

    public boolean hasPathSum(TreeNode root, int targetSum) {
        isSum = false;
        if (root == null) {
            return isSum;
        }
        hasPathSumChild(root, 0, targetSum);
        return isSum;
    }

    public void hasPathSumChild(TreeNode root, int preSum, int targetSum) {
        // 当是叶子结点的时候
        if (root.left == null && root.right == null) {
            if (root.val + preSum == targetSum) {
                isSum = true;
            }
        }
        preSum += root.val;
        // 当不是叶子结点的时候
        if (root.left != null) {
            hasPathSumChild(root.left,preSum,targetSum);
        }
        if (root.right != null) {
            hasPathSumChild(root.right,preSum,targetSum);
        }
    }
}
